import { validSpaceSpecialCharEmoji } from "@utils/validate";
import { jsonp } from 'vue-jsonp' //使用jsonp

export default {
    mounted() {
        this.addListenAddress();
    },
    data() {
        return {
            getLocationInfo: {
                getLat: "",
                getLng: "",
                province: "",
                city: "",
                area: "",
                street: "",
                address: "",
            },
            getAddressflag: false, //地图选点
        };
    },
    methods: {
        // 监听获取经纬度
        addListenAddress() {
            window.addEventListener(
                "message",
                (event) => {
                    // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
                    let loc = event.data;
                    if (loc && loc.module == "locationPicker") {
                        //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
                        this.getAddress(loc.latlng.lat, loc.latlng.lng, loc.poiname);
                    }
                },
                false
            );
        },
        // 获取地址信息
        getAddress(lat, lng, poiname) {
            jsonp(
                    `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53`, {
                        output: "jsonp",
                    }
                )
                .then((res) => {
                    this.getAddressflag = !this.getAddressflag;
                    // console.log(res);
                    let { province, city, district } = res.result.ad_info;
                    let { title } = res.result.address_reference.town;
                    this.$set(this.getLocationInfo, "getLat", lat);
                    this.$set(this.getLocationInfo, "getLng", lng);
                    this.$set(this.getLocationInfo, "province", province);
                    this.$set(this.getLocationInfo, "city", city);
                    this.$set(this.getLocationInfo, "area", district);
                    this.$set(this.getLocationInfo, "street", title);
                    this.$set(
                        this.getLocationInfo,
                        "address",
                        this.stripscript(poiname).length > 20 ?
                        this.stripscript(poiname).substr(0, 20) :
                        this.stripscript(poiname)
                    );
                })
                .catch((err) => {
                    // console.log(err, "err");
                });
        },
        // 过滤特殊字符
        stripscript(s) {
            let pattern = new RegExp(
                "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]"
            );
            let rs = "";
            for (let i = 0; i < s.length; i++) {
                rs = rs + s.substr(i, 1).replace(pattern, "");
            }
            return rs;
        },
    },
};